<?php
namespace app\api\controller\iot;

use app\api\controller\Base;
use app\api\controller\mytool\Setting;
use app\common\model\user\User as UserModel;
use app\api\controller\datascreen\Index as dataScreenIndex;
use Firebase\JWT\JWT;
use think\facade\Cache;
use app\common\model\transit\Transport;

class Tuhugc extends Base
{
    //http://openapi.tuhugc.com/jiekouxiangqing/renzhengshuoming.html
    //接口文档

    private $url = 'http://open.tuhugc.com';
    // private $appKey = 'testkey001';
    // private $appsecret = 'testsecret001';
    // private $username = '15156981372';

    private $appKey    = '';
    private $appsecret = '';
    private $username  = '';

    // private $appKey = 'bb59f9beb3460306845cf30904f6fdd4';
    // private $appsecret = '7789d2bddc11ed1335565c26221cd716';
    // private $username = '15511313142';

    /**
     * 产生jwt加密串，参考session
     */
    public function initialize()
    {
        parent::initialize();
        $this->appKey = get_config_value('iot_tuhugc_appKey');
        $this->appsecret = get_config_value('iot_tuhugc_appsecret');
        $this->username = get_config_value('iot_tuhugc_username');
        if(empty($this->appKey)){
            moerr('缺少iot-Tuhugc-appkey');
        }
    }

    /**
     * 获取参数
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function getsign($data)
    {
        // 第一步：排序
        ksort($data);
        // 第二步：把所有参数名和参数值串在一起
        $str = '';
        foreach ($data as $key => $value) {
            $str = $str . $key . $value;
        }
        $str = $this->appsecret . $str . $this->appsecret;
        // 第三步：使用MD5/HMAC加密
        $str = md5($str);
        return strtoupper($str);
    }

    /**
     * 获取通用参数
     * @param  [type] $sign [description]
     * @return [type]       [description]
     */
    public function get_url_option($data)
    {
        $str = '';
        foreach ($data as $key => $value) {
            if ($str == '') {
                $str = '?' . $key . '=' . $value;
            } else {
                $str = $str . '&' . $key . '=' . $value;
            }
        }
        return $str;
    }

    /**
     * 获取登陆的token
     * @return [type] [description]
     */
    public function gettoken($refresh= false)
    {
        $token = Cache::get('Tuhugc_token' . $this->username);
        if (!empty($token)&&$refresh!==true) {
            return sok($token);
        }
        $data = [
            'userId'    => $this->username,
            'expiresIn' => '7200',
            'timestamp' => date('Y-m-dH:i:s', time()),
            'appKey'    => $this->appKey,
            'v'         => '1.0',
        ];
        $data['sign'] = self::getsign($data);
        $uurl         = $this->url . '/v1/token/get' . self::get_url_option($data);
        $sb           = self::https_request($uurl);
        $res          = json_array($sb, true);
        $msg          = empty($res['message']) ? '' : $res['message'];
        if (empty($res['result']['accessToken'])) {
            return serr('没有找到tuhu设备token。' . $msg);
        }
        $token = $res['result']['accessToken'];
        Cache::set('Tuhugc_token' . $this->username, $token, 7000);
        return sok($token);
    }

    /**
     * 根据账户获取所有设备的最新定位数据
     * @return [type] [description]
     */
    public function getcarlist()
    {
		// dataScreenIndex::is_login();
        $sb = Cache::get('user_car_list_lapse');//出错缓存标志
        $upper_limit = false;//是否出错
        if(empty($sb)){
            $data = self::getuser_car_list();
            if($data['code']==1010){
                $upper_limit = true;
            }
        }else{
            $upper_limit = true;
        }
        //出错后调用另一个接口
        if($upper_limit){
            $data = self::getcar_imei_list();
        }
        return myok($data);
    }

    /**
     * 获取用户下面所有imei的车辆
     * @return [type] [description]
     */
    public function getuser_car_list()
    {
        $switch = Setting::get_screen_show_car_list();
        if(!$switch){
            return myerr('暂未开启此功能'); 
        }
        $data   = [
            'userId'    => $this->username,
            'mapType'   => 'GOOGLE',
            'timestamp' => date('Y-m-dH:i:s', time()),
            'appKey'    => $this->appKey,
            'v'         => '1.0',
        ];
        $data['sign'] = self::getsign($data);
        $uurl         = $this->url . '/v1/device/location/list' . self::get_url_option($data);
        $sb           = self::https_request($uurl, '', true);
        $res          = json_array($sb, true);
        return sok($res['result']);
    }

    /**
     * 根据账户获取所有设备的最新定位数据
     * @return [type] [description]
     */
    public function getcar_imei_list()
    {
        // dataScreenIndex::is_login();
        $switch = Setting::get_screen_show_car_list();
        if(!$switch){
            return myerr('暂未开启此功能'); 
        }
        $data   = [
            'userId'    => $this->username,
            'mapType'   => 'GOOGLE',
            'timestamp' => date('Y-m-dH:i:s', time()),
            'appKey'    => $this->appKey,
            'v'         => '1.0',
        ];
        $data['imeis'] =Transport::get_imei_list();
        $data['sign'] = self::getsign($data);
        $uurl         = $this->url . '/v1/device/location/get'; //. self::get_url_option($data);
        $sb           = self::https_request($uurl, $data, true);
        $res          = json_array($sb, true);
        return sok($res['result']);
    }


    /**
     * 获取设备的轨迹信息
     * @return [type] [description]
     */
    public function gettracklist()
    {
        dataScreenIndex::is_login();
        $switch = Setting::get_screen_show_car_list();
        if(!$switch){
            return myerr('暂未开启此功能'); 
        }
        $imei = input('imei');
        if(empty($imei)){
            return myerr('缺少车辆信息');
        }
        
        $startime = input('startime');
        if(empty($startime)){$startime = date('Y-m-d 00:00:00',time());}else{$startime = date('Y-m-d 00:00:00',strtotime($startime));}
        $endtime = input('endtime');
        if(empty($endtime)){$endtime = date('Y-m-d 23:59:59',time());}else{$endtime = date('Y-m-d 23:59:59',strtotime($endtime));}
        //通用变量 + 私有变量
        $data   = [
            'userId'    => $this->username,
            'mapType'   => 'GOOGLE',
            'appKey'    => $this->appKey,
            'v'         => '1.0',
            //私有参数
            'imei'      => $imei,
            'startTime' =>$startime,
            'endTime'   =>$endtime,
        ];
        $data['sign'] = self::getsign($data);
        $uurl         = $this->url . '/v1/device/track/list' ;//. self::get_url_option($data);
        $sb           = self::https_request($uurl, $data, true);
        $res          = json_array($sb, true);
        return myok($res['result']);
    }

    /**
     * 网址编码
     * @param  [type] $url [description]
     * @return [type]      [description]
     */
    public function encodeURI($url)
    {
        $unescaped = array(
            '%2D' => '-', '%5F' => '_', '%2E' => '.', '%21' => '!', '%7E' => '~',
            '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')',
        );
        $reserved = array(
            '%3B' => ';', '%2C' => ',', '%2F' => '/', '%3F' => '?', '%3A' => ':',
            '%40' => '@', '%26' => '&', '%3D' => '=', '%2B' => '+', '%24' => '$',
        );
        $score = array(
            '%23' => '#',
        );
        return strtr(rawurlencode($url), array_merge($reserved, $unescaped, $score));

    }

    /**
     * 请求
     * @param  [type] $url  [description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    protected function https_request($url, $data = null, $token = false,$refresh = false)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //下面这行是修改后增加的代码，就是配置设置host访问，发送的数据类型为application/json
        $length = 0;
        if(is_array($data)){
            $length = 0;
            foreach ($data as $key => $value) {
                $length = $length + strlen($value);
            }
        }else{
            $length = strlen($data);
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
            'Content-Length: ' .$length,
        ));
        if ($token == true) {
            $tk = self::gettoken($refresh);
            if (!$tk['code']) {
                return moerr($tk['msg']);
            }
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'X-Access-Token:' . $tk['msg'],
            ));
        }
        $output = curl_exec($curl);
        curl_close($curl);
        try {
            $sb = json_array($output);
            if($sb['success']==false){
               switch ($sb['code']) {
                    case '1007':
                        if($refresh==false){
                            if(!empty($sb['code'])&&$sb['code']=='1007'&&$sb['message']=='token失效，请刷新或重新获取！ '){
                                return self::https_request($url, $data, $token,true);
                            }   
                        }
                    break;
                    case '1010':
                        //接口次数调用达到限制
                    break;
                    default:
                       return moerr($sb['message']);
                    break;
               }
            }
            
        } catch (\Exception $e) {}
        return $output;
    }

    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = Setting::login_screen_password(input('scp'));
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
}
